package com.example.reagent_management.service.works

import android.content.Context
import android.util.Log
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.ForegroundInfo
import androidx.work.WorkerParameters
import com.example.reagent_management.room.dao.HistoryDao
import com.example.reagent_management.room.entity.HistoryInfo
import com.example.reagent_management.ui.operatedialog.repository.HistoryRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import java.lang.Exception

/**
 * 插入历史
 */
//关于WorkManager请参考
// https://developer.android.google.cn/topic/libraries/architecture/workmanager/how-to/define-work#schedule_periodic_work
@HiltWorker  // 常见的注入的后台有 比如数据操作对象 以及后台网络的apiService注入等等  //Work也提供了可观察的LiveData结果返回对象
class HistoryWork @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted workerParameters: WorkerParameters,
    private val historyRepository: HistoryRepository
) :
    CoroutineWorker(context, workerParameters) {
    override suspend fun doWork(): Result {
        return withContext(Dispatchers.IO) {
            //Data类型目前不支持传对象
            val historyInfoString =
                inputData.getStringArray(HISTORY_INFO_STRING) ?: return@withContext Result.failure()
            val historyInfoLong =
                inputData.getLongArray(HISTORY_INFO_LONG) ?: return@withContext Result.failure()
            val historyInfoBoolean = inputData.getBoolean(HISTORY_INFO_BOOLEAN, true)
            val updateFlag = inputData.getBoolean(HISTORY_UPDATE,false)
            val result: Deferred<Long> = if (updateFlag){
                async {
                    return@async historyRepository.updateReagent( historyInfoLong[0],historyInfoString[0]).toLong()
                }
            }else {
                async {
                    return@async historyRepository.insertHistory(
                        HistoryInfo(historyInfoString[0],historyInfoString[1],
                            historyInfoLong[0],historyInfoLong[1],historyInfoLong[2],historyInfoLong[3],
                            historyInfoBoolean))
                }
            }

            if (result.await() == -1L || result.await() != 0L){
                Result.failure()
            }
            Log.e(TAG, "doWork: ${result.await()}")
            Result.success()
        }
    }

    companion object {
        const val TAG = "HistoryWork"

        const val HISTORY_INFO_STRING = "History_Info_String"
        const val HISTORY_INFO_LONG = "History_Info_LONG"
        const val HISTORY_INFO_BOOLEAN = "History_Info_Boolean"

        const val HISTORY_UPDATE = "History_Update_Reagent"

        const val INSERT_HISTORY_RESULT = "INSERT_HISTORY"
    }
}